import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an8 from '@mmstudio/an000008';
import an48 from '@mmstudio/an000048';
import { tbcurriculum } from '../../../../atoms/db';

const logger = anylogger('pages/api/professional/course/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = Omit<ITbcurriculum, 'curriculum_id'>;

/**
 * 新增课程
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;

		if (!body
			|| !body.courseintroduction
			|| !body.coursename
			|| !body.credit
			|| !body.group_id
			|| !body.major_id
			|| !body.semester
			|| !body.type
		) {
			res.status(200).json({
				ok: false,
				message: '缺少必要的参数'
			});
			return;
		}
		const course = await tbcurriculum().first('*').where({
			major_id: body.major_id,
			group_id: body.group_id,
			coursename: body.coursename
		});
		if (course) {
			res.status(200).json({ ok: false, message: '课程已存在' });
			return;
		}
		const curriculum_id = an8();
		await tbcurriculum().insert({
			...body,
			curriculum_id

		});
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
